<template>
	<div class="wrapper">

		<!-- header部分 -->
		<header>
			<p>我的订单</p>
		</header>

		<!-- 订单列表部分 -->
		<h3>未支付订单信息：</h3>
		<ul class="order">
			<li v-for="item in validOrders" v-if="item.orderState==0" :key="item.id">
				<div class="order-info">
					<p>
						{{item.business.businessName}}
						<i class="fa fa-caret-down" @click="detailetShow(item)"></i>
					</p>
					<div class="order-info-right">
						<p>&#165;{{item.orderTotal}}</p>
						<div class="order-info-right-icon" @click="goToPayment(item.id)">去支付</div>
						<div class="order-info-right-delete" @click="deleteOrder(item.id, item)">删除</div>
					</div>
				</div>
				<ul class="order-detailet" v-show="item.isShowDetailet">
					<li v-for="odItem in item.list" :key="odItem.id">
						<p>{{odItem.food.foodName}} x {{odItem.quantity}}</p>
						<p>&#165;{{odItem.food.foodPrice*odItem.quantity}}</p>
					</li>
					<li>
						<p>配送费</p>
						<p>&#165;{{item.business.deliveryPrice}}</p>
					</li>
				</ul>
			</li>
		</ul>

		<h3>已支付订单信息：</h3>
		<ul class="order">
			<li v-for="item in validOrders" v-if="item.orderState==1" :key="item.id">
				<div class="order-info">
					<p>
						{{item.business.businessName}}
						<i class="fa fa-caret-down" @click="detailetShow(item)"></i>
					</p>
					<div class="order-info-right">
						<p>&#165;{{item.orderTotal}}</p>
						<div class="order-info-right-delete" @click="deleteOrder(item.id, item)">删除</div>
					</div>
				</div>
				<ul class="order-detailet" v-show="item.isShowDetailet">
					<li v-for="odItem in item.list" :key="odItem.id">
						<p>{{odItem.food.foodName}} x {{odItem.quantity}}</p>
						<p>&#165;{{odItem.food.foodPrice*odItem.quantity}}</p>
					</li>
					<li>
						<p>配送费</p>
						<p>&#165;{{item.business.deliveryPrice}}</p>
					</li>
				</ul>
			</li>
		</ul>

		<!-- 底部菜单部分 -->
		<Footer></Footer>

	</div>
</template>

<script>
import Footer from '../components/Footer.vue';

export default{
    name:'OrderList',
    data(){
        return {
            orderArr:[], // 存储所有订单（包括已删除的）
            user:{},
            isDeleting: false // 防止重复提交
        }
    },
    computed: {
        // 过滤掉已删除的订单
        validOrders() {
            return this.orderArr.filter(order => !order.isDeleted);
        },
        unpaidOrders() {
            return this.validOrders.filter(order => order.orderState === 0);
        },
        paidOrders() {
            return this.validOrders.filter(order => order.orderState === 1);
        }
    },
    created() {
        this.user = this.$getLocalStorage('user');
        this.fetchOrders();
    },
    methods:{
        fetchOrders() {
            return this.$axios.get('/api/orders', {
                params: {
                    userId: this.user.id
                }
            }).then(response => {
                let result = response.data;
                console.log('获取订单接口返回:', result);
                
                if (result.success && Array.isArray(result.data)) {
                    // 保存所有订单（包括已删除的）
                    this.orderArr = result.data.map(order => ({
                        ...order,
                        isDeleted: order.isDeleted || false, // 确保有isDeleted字段
                        isShowDetailet: false,
                        business: {
                            businessName: order.businessName,
                            deliveryPrice: order.deliveryPrice || 0
                        },
                        list: order.orderDetailets ? order.orderDetailets.map(detail => ({
                            ...detail,
                            food: {
                                foodName: detail.foodName,
                                foodPrice: detail.itemPrice
                            }
                        })) : []
                    }));
                    
                    console.log('处理后的订单列表（包含已删除）:', this.orderArr);
                    console.log('过滤后的有效订单:', this.validOrders);
                } else {
                    console.error('获取订单失败:', result.message || '未知错误');
                }
                return result;
            }).catch(error => {
                console.error('请求订单接口出错:', error);
                throw error;
            });
        },
        
        detailetShow(orders){
            orders.isShowDetailet = !orders.isShowDetailet;
        },
        
        goToPayment(orderId) {
            this.$router.push({
                path: '/payment',
                query: { orderId: orderId }
            });
        },
        
        deleteOrder(orderId, orderItem) {
            if (this.isDeleting) return;
            
            console.log('准备删除的订单ID:', orderId);
            console.log('当前订单对象:', orderItem);
            
            if (window.confirm(`确定要删除订单 ${orderId} 吗？`)) {
                this.isDeleting = true;
                
                this.$axios.delete(`/api/orders/${orderId}`)
                    .then(response => {
                        console.log('删除接口返回的完整响应:', response);
                        let result = response.data;
                        
                        if (result.success) {
                            console.log('删除成功，更新订单状态...');
                            
                            // 更新订单的isDeleted状态为true
                            const orderIndex = this.orderArr.findIndex(order => order.id === orderId);
                            if (orderIndex !== -1) {
                                this.orderArr[orderIndex].isDeleted = true;
                                // 使用Vue.set确保响应式更新
                                this.$set(this.orderArr, orderIndex, {...this.orderArr[orderIndex]});
                            }
                            
                            console.log('更新后的订单列表:', this.orderArr);
                            alert('订单删除成功');
                        } else {
                            console.error('删除失败，返回信息:', result);
                            alert(`删除失败: ${result.message || '服务器处理失败'}`);
                        }
                    })
                    .catch(error => {
                        console.error('删除请求发生错误:', error);
                        let errorMsg = '网络异常，删除失败';
                        if (error.response) {
                            const result = error.response.data;
                            console.error('删除错误详情:', result);
                            errorMsg = result.message || result.code || `服务器错误，状态码: ${error.response.status}`;
                        }
                        alert(errorMsg);
                    })
                    .finally(() => {
                        this.isDeleting = false;
                    });
            }
        }
    },
    components:{
        Footer
    }
}
</script>


<style scoped>
	/****************** 总容器 ******************/
	.wrapper {
		width: 100%;
		height: 100%;
	}

	/****************** header部分 ******************/
	.wrapper header {
		width: 100%;
		height: 12vw;
		background-color: #0097FF;
		color: #fff;
		font-size: 4.8vw;

		position: fixed;
		left: 0;
		top: 0;
		z-index: 1000;

		display: flex;
		justify-content: center;
		align-items: center;
	}

	/****************** 历史订单列表部分 ******************/
	.wrapper h3 {
		margin-top: 12vw;
		box-sizing: border-box;
		padding: 4vw;
		font-size: 4vw;
		font-weight: 300;
		color: #999;
	}

	.wrapper .order {
		width: 100%;
	}

	.wrapper .order li {
		width: 100%;
	}

	.wrapper .order li .order-info {
		box-sizing: border-box;
		padding: 2vw 4vw;
		font-size: 4vw;
		color: #666;

		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.wrapper .order li .order-info .order-info-right {
		display: flex;
	}

	.wrapper .order li .order-info .order-info-right .order-info-right-icon {
		background-color: #f90;
		color: #fff;
		border-radius: 3px;
		margin-left: 2vw;
		user-select: none;
		cursor: pointer;
		padding: 1vw 2vw;
	}

	/* 删除按钮样式 */
	.wrapper .order li .order-info .order-info-right .order-info-right-delete {
		background-color: #999;
		color: #fff;
		border-radius: 3px;
		margin-left: 2vw;
		user-select: none;
		cursor: pointer;
		padding: 1vw 2vw;
	}

	/* 加载中状态样式 */
	.wrapper .order li .order-info .order-info-right .order-info-right-delete.loading {
		background-color: #ccc;
		cursor: not-allowed;
	}

	.wrapper .order li .order-detailet {
		width: 100%;
	}

	.wrapper .order li .order-detailet li {
		width: 100%;
		box-sizing: border-box;
		padding: 1vw 4vw;
		color: #666;
		font-size: 3vw;

		display: flex;
		justify-content: space-between;
		align-items: center;
	}
</style>
    